package com.karina.visualization.chart.skins;

import java.util.List;

import com.karina.visualization.chart.client.Color;
import com.karina.visualization.chart.client.Graphics;
import com.karina.visualization.chart.model.CategorizedSeriesModel;
import com.karina.visualization.chart.model.SeriesModel.CategoryValue;

public class LineSkin extends BaseSkin<CategorizedSeriesModel> {
	protected CategorizedSeriesModel data;
	protected Color current_color;

	@Override
	public void setData(CategorizedSeriesModel data) {
		this.data = data;
	}

	@Override
	public CategorizedSeriesModel getData() {
		return data;
	}

	@Override
	public void draw(Graphics graphics) {
		double x = data.getX() + data.getMarginLeft();
		double y = data.getY();
		List<CategoryValue> values = data.getValue();
		double max = data.getMaxValue();
		int height = data.getHeight() - data.getMarginBottom();
		int gap = (graphics.getCoordWidth() - data.getMarginLeft()
				- data.getX() - data.getRight())
				/ (values.size() - 1);

		if (current_color == null) {
			current_color = Graphics.PRE_DEFINED_COLOR_ARRAY[data.getIndex()];
		}
		graphics.saveContext();

		int i = 0;

		graphics.setLineWidth(3);
		double sx = 0;
		double sy = 0;
		double tx = 0;
		double ty = 0;
		for (CategoryValue category : values) {
			double value = Double.parseDouble(category.getValue().toString());
			double h = (value / max) * height;
			tx = x;
			ty = y + height - h;

			graphics.shallow(4, 4, 6, 204, 204, 204, 0.8);

			drawPoint(graphics, tx, ty);

			i = drawLine(graphics, i, sx, sy, tx, ty);

			sx = tx;
			sy = ty;
			x += gap;
		}

		graphics.restoreContext();

	}

	protected int drawLine(Graphics graphics, int i, double sx, double sy,
			double tx, double ty) {
		graphics.beginPath();
		graphics.setLineColor(current_color.r, current_color.g,
				current_color.b, 1.0);

		if (i == 0) {
			graphics.moveTo(tx, ty);
			i++;
		} else {

			String style = (String) getStyleDeclaretion(".LineSeries")
					.getStyle("lineStyle");
			if ("curve".equals(style)) {
				double cx1 = sx / 2 + tx / 2;
				double cy1 = sy;
				double cx2 = sx / 2 + tx / 2;
				double cy2 = ty;
				graphics.drawBezierChart(sx, sy, cx1, cy1, cx2, cy2, tx, ty);
			} else {
				graphics.moveTo(sx, sy);
				graphics.lineTo(tx, ty);
			}
		}
		graphics.stroke();
		graphics.endPath();

		return i;
	}

	protected void drawPoint(Graphics graphics, double tx, double ty) {
		graphics.fillStyle(current_color.r, current_color.g, current_color.b,
				1.0);

		graphics.beginPath();
		graphics.drawCircle(tx, ty, 4);
		graphics.fill();
		graphics.endPath();
	}

	@Override
	public void cleanup(Graphics graphics) {
		// graphics.clear();
	}

	@Override
	public void refresh(Graphics graphics) {
		cleanup(graphics);
		draw(graphics);
	}

}
